﻿using Ldt.DataEngine.RuleAssemble;
using LdtDataEngin.ModuleDetail.CaseElmentOpt;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.CommModel;
using LdtJudge.DataEngine.Model.EvidenceFact;
using LdtJudge.DataEngine.Model.XMLConfigModel.CommModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.BaseModule.Optimization
{
    public class OptimizationBase
    {
        #region 基础信息

        /// <summary>
        /// 配置信息
        /// </summary>
        public OptimizeConfig OptimizConfig { get; set; }

        /// <summary>
        /// 相同合并方式
        /// </summary>
        public MergeModel mergeModel { get; set; }

        /// <summary>
        /// 案由要素优选配置
        /// </summary>
        public OptimizeElementConfig OptimizeElement { get; set; }

        /// <summary>
        /// 标识信息
        /// </summary>
        public RootDossierinfo RootDossierinfoModel { get; set; }

        /// <summary>
        /// 相同文书合并配置
        /// </summary>
        public XmlMultipleConfig XmlMultipleConfigModel { get; set; }

        /// <summary>
        /// 分析结果数据标签
        /// </summary>
        public string DataSourceResult { get; set; }

        /// <summary>
        /// 上一阶段数据源标签
        /// </summary>
        public string DataSourceParent { get; set; }

        /// <summary>
        /// 优选模块名称
        /// </summary>
        public string ModuleName { get; set; }

        /// <summary>
        /// 上下文
        /// </summary>
        public DataContext dataContext;

        /// <summary>
        /// 数据保存基础路径
        /// </summary>
        private string SaveUrl = ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("ldt.elementcenterfilestore");

        /// <summary>
        /// 相同文书标识配置
        /// </summary>

        public string multipledocjudge;

        /// <summary>
        /// 相同文书优选配置
        /// </summary>
        public string docmergeopt;
        #endregion


        #region 要素去重

        public XmlDocument EscapeNodeIndexAndBlank(XmlDocument docxml)
        {
            ///去除只有序号的节点信息
            //docxml = EscapeNodeIndex(docxml);
            ///去除空节点
            docxml = EscapeBlank(docxml);

            return docxml;
        }
        /// <summary>
        /// 去除xml中的空节点
        /// </summary>//*[not(attribute::*) and not (child::*)]
        /// <param name="second">待去除xml</param>
        /// <returns>取出后的结果</returns>
        protected XmlDocument EscapeBlank(XmlDocument second)
        {
            XmlNodeList blanks = second.SelectNodes("//*[ not (child::*)]");//取无属性 无子节点的节点
            while (blanks.Count > 0)
            {
                bool flag = true;

                foreach (XmlNode node in blanks)
                {
                    if (node.Attributes["id"] != null && node.Attributes.Count == 1)
                    {
                        if (node.ParentNode != null && node.ParentNode.ParentNode != null)
                        {
                            node.ParentNode.RemoveChild(node);
                        }
                        else
                        {
                            flag = false;
                        }
                    }
                    else
                    {
                        flag = false;
                    }

                }
                blanks = second.SelectNodes("//*[ not (child::*)]");//递归查询

                if (!flag)
                {
                    break;
                }

            }
            return second;
        }
        #endregion

        #region 配置加载

        /// <summary>
        /// 转换出数据源实体
        /// </summary>
        /// <returns></returns>
        public DataSoursModel GetDataSoursModel(XmlDocument xmlDocument)
        {
            DataSoursModel soursModel = new DataSoursModel();
            if (!string.IsNullOrEmpty(xmlDocument.OuterXml))
            {
                soursModel = XmlUtility.DeserializeToObject<DataSoursModel>(xmlDocument.OuterXml.Replace("&#x", ""));
                foreach (DataModel dataModel in soursModel.dataModelList)
                {
                    dataModel.XmlPath = dataModel.XmlPath.Replace("\\", "/");
                }
            }

            return soursModel;
        }
        /// <summary>
        /// 加载相同配置数据
        /// </summary>
        /// <param name="dataModelAsisList">分析提取数据</param>
        /// <param name="dataModelsOPList">上次优选结果数据</param>
        /// <param name="type">数据类型 1.案件要素 2.案由要素</param>
        public void MergConfig(List<DataModel> dataModelAsisList,List<DataModel> dataModelsOPList,string type) 
        {
            try
            {
                if (!string.IsNullOrEmpty(multipledocjudge))
                {
                    //多次开庭配置加载
                    MultipleSginModel(multipledocjudge);
                    //多次开庭类型判定
                    if (RootDossierinfoModel != null)
                    {
                        //进入多次开庭
                        DossierinfoModel dossierinfoModel = RootDossierinfoModel.DossierinfoList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
                        if (dossierinfoModel != null)
                        {
                            if (dossierinfoModel.Iscover == "1")
                            {
                                //覆盖模式
                                FormatDataSource formatDataSourcenew = new FormatDataSource(dataContext);
                                if (type=="1")
                                {
                                    formatDataSourcenew.FromatNodeList(dataModelsOPList);
                                }
                                else if (type=="2")
                                {
                                    formatDataSourcenew.FromatNodeListCasue(dataModelsOPList);
                                }
                               
                            }
                            else if (dossierinfoModel.Iscover == "0")
                            {
                                if(!string.IsNullOrEmpty(docmergeopt))
                                {
                                    mergeModel = new MergeModel();
                                    MultipleModel(docmergeopt);
                                    mergeModel.xmlMultiple = XmlMultipleConfigModel;
                                    //填充优选模式
                                    if (dossierinfoModel.SinggroupList != null)
                                    {
                                        MultipleLoadeData(dossierinfoModel.SinggroupList[0], dataModelAsisList, dataModelsOPList, type);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                dataContext.InteractiveShow.LogShow("相同文书配置错误");
            }
            
           
        }

        public void RomveData(List<DataModel> dataModelsOPList)
        {
            FormatDataSource formatDataSourcenew = new FormatDataSource(dataContext);
            formatDataSourcenew.FromatNodeListCasue(dataModelsOPList);
        }

        /// <summary>
        /// 多次开庭数据加载
        /// </summary>
        /// <param name="singgroup"></param>
        public void MultipleLoadeData(Singgroup singgroup, List<DataModel> dataModelAsisList, List<DataModel> dataModelOPList,string type)
        {
            Singgroup singgroupAsis = JsonConvert.DeserializeObject<Singgroup>(JsonConvert.SerializeObject(singgroup));
            Singgroup singgroupOp = JsonConvert.DeserializeObject<Singgroup>(JsonConvert.SerializeObject(singgroup));

            dossierSignLoade(singgroupAsis.dossierSign, dataModelAsisList);
            dossierSignLoade(singgroupOp.dossierSign, dataModelOPList);
            #region 暂时去除标识相同文书判断逻辑
            ////是否为标识相同文书@@
            //bool IsMulltiple = MulltipleCompare(singgroupAsis.dossierSign, singgroupOp.dossierSign);
            //if (IsMulltiple)
            //{
            //    //标识相同文书
            //    FormatDataSource formatDataSourcenew = new FormatDataSource(dataContext);

            //    if (type == "1")
            //    {
            //        formatDataSourcenew.FromatNodeList(dataModelOPList, dataContext.DataLayerAns.SF_ID, dataContext.DataLayerAns.FL_ID);
            //    }
            //    else if (type == "2")
            //    {
            //        formatDataSourcenew.FromatNodeListCasue(dataModelOPList);
            //    }
            //}
            #endregion
            //标识相同文书
            FormatDataSource formatDataSourcenew = new FormatDataSource(dataContext);
            if (type == "1")
            {
                formatDataSourcenew.FromatNodeList(dataModelOPList, dataContext.DataLayerAns.SF_ID, dataContext.DataLayerAns.FL_ID);
            }
            else if (type == "2")
            {
                formatDataSourcenew.FromatNodeListCasue(dataModelOPList, dataContext.DataLayerAns.SF_ID, dataContext.DataLayerAns.FL_ID);
            }

        }
        /// <summary>
        /// 对dossierSign实体进行填充
        /// </summary>
        /// <param name="singgroup">实体信息</param>
        /// <param name="dataModelList"></param>
        public void dossierSignLoade(DossierSign dossierSign, List<DataModel> dataModelList)
        {
            if (dossierSign != null)
            {
                string xmlpath = dossierSign.Filed;
                string attname = "";
                if (xmlpath.IndexOf("/@") > -1)
                {
                    string[] str = xmlpath.Split(new string[] { "/@" }, StringSplitOptions.None);
                    if (str.Length == 2)
                    {
                        xmlpath = str[0];
                        attname = str[1];
                    }
                }

                if (!string.IsNullOrEmpty(attname))
                {
                    DataModel dataModel = XmlUtility.ConditionFirstOrDefaultDataModel(dataModelList, "", xmlpath);
                    if (dataModel != null)
                    {
                        AttributeInfo attributeInfo = dataModel.AttributesList.FirstOrDefault(a => a.Name == attname);
                        if (attributeInfo != null)
                        {
                            string value = attributeInfo.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                            dossierSign.value = value;
                            if (dossierSign.dossierinfoModel != null)
                            {
                                dossierSignLoade(dossierSign.dossierinfoModel, dataModelList);
                            }

                        }
                    }
                }
            }

        }
        public bool MulltipleCompare(DossierSign dossierSignAsis, DossierSign dossierSignOp)
        {
            if (dossierSignAsis.value == dossierSignOp.value)
            {
                if (dossierSignAsis.dossierinfoModel != null && dossierSignOp.dossierinfoModel != null)
                {
                    if (MulltipleCompare(dossierSignAsis.dossierinfoModel, dossierSignOp.dossierinfoModel))
                    {
                        return true;
                    }
                    else
                    {
                        if (dossierSignAsis.CompareType == "1")
                        {
                            //数字类型判定
                            try
                            {
                                int valueone = int.Parse(dossierSignAsis.value);
                                int valuetow = int.Parse(dossierSignOp.value);
                                if (valueone > valuetow)
                                {
                                    mergeModel.AsisModle = "max";
                                    mergeModel.OPModle = "min";
                                }
                                else if (valueone < valuetow)
                                {
                                    mergeModel.AsisModle = "main";
                                    mergeModel.OPModle = "max";
                                }

                            }
                            catch (Exception ex)
                            {

                                dataContext.InteractiveShow.LogShow("相同文书转换，转INT类型失败");
                            }
                        }
                        else if (dossierSignAsis.CompareType == "2")
                        {
                            //时间判定
                            try
                            {
                                DateTime valueone = DateTime.Parse(dossierSignAsis.value);
                                DateTime valuetow = DateTime.Parse(dossierSignOp.value);
                                if (valueone > valuetow)
                                {
                                    mergeModel.AsisModle = "max";
                                    mergeModel.OPModle = "min";
                                }
                                else if (valueone < valuetow)
                                {
                                    mergeModel.AsisModle = "main";
                                    mergeModel.OPModle = "max";
                                }

                            }
                            catch (Exception ex)
                            {

                                dataContext.InteractiveShow.LogShow("相同文书转换，转DateTime类型失败");
                            }
                        }
                        else if (dossierSignAsis.CompareType == "3")
                        {
                            //创建时间优选
                            mergeModel.AsisModle = "max";
                            mergeModel.OPModle = "min";

                        }

                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            else
            {
                if (dossierSignAsis.CompareType == "1")
                {
                    //数字类型判定
                    try
                    {
                        int valueone = int.Parse(dossierSignAsis.value);
                        int valuetow = int.Parse(dossierSignOp.value);
                        mergeModel = new MergeModel();
                        if (valueone > valuetow)
                        {
                            mergeModel.AsisModle = "max";
                            mergeModel.OPModle = "min";
                        }
                        else if (valueone < valuetow)
                        {
                            mergeModel.AsisModle = "main";
                            mergeModel.OPModle = "max";
                        }

                    }
                    catch (Exception ex)
                    {

                        dataContext.InteractiveShow.LogShow("相同文书转换，转INT类型失败");
                    }
                }
                else if (dossierSignAsis.CompareType == "2")
                {
                    //时间判定
                    try
                    {
                        DateTime valueone = DateTime.Parse(dossierSignAsis.value);
                        DateTime valuetow = DateTime.Parse(dossierSignOp.value);
                        if (valueone > valuetow)
                        {
                            mergeModel.AsisModle = "max";
                            mergeModel.OPModle = "min";
                        }
                        else if (valueone < valuetow)
                        {
                            mergeModel.AsisModle = "main";
                            mergeModel.OPModle = "max";
                        }

                    }
                    catch (Exception ex)
                    {

                        dataContext.InteractiveShow.LogShow("相同文书转换，转DateTime类型失败");
                    }
                }
                else if (dossierSignAsis.CompareType == "3")
                {
                    //创建时间优选
                    mergeModel = new MergeModel();
                    mergeModel.AsisModle = "max";
                    mergeModel.OPModle = "min";
                }
                return false;
            }
        }

        /// <summary>
        /// 初始化配置
        /// </summary>
        /// <param name="xmlContext">XML内容/路径</param>
        public void OptimizationConfig(string xmlContext)
        {
            if (!string.IsNullOrEmpty(xmlContext))
            {
                OptimizConfig = XmlUtility.DeserializeToObject<OptimizeConfig>(xmlContext);
            }

        }

        /// <summary>
        /// 相同文书标识配置加载
        /// </summary>
        /// <param name="xmlContext"></param>
        public void MultipleSginModel(string xmlContext)
        {
            if (!string.IsNullOrEmpty(xmlContext))
            {
                RootDossierinfoModel = XmlUtility.DeserializeToObject<RootDossierinfo>(xmlContext);
            }
        }

        /// <summary>
        /// 相同文书合并配置
        /// </summary>
        /// <param name="xmlContext"></param>
        public void MultipleModel(string xmlContext)
        {
            XmlMultipleConfigModel = XmlUtility.DeserializeToObject<XmlMultipleConfig>(xmlContext);
        }

        /// <summary>
        /// 优选数据配置
        /// </summary>
        /// <param name="xmlContext"></param>
        public void OptimizationElementConfig(string xmlContext)
        {
            if (!string.IsNullOrEmpty(xmlContext))
            {
                OptimizeElement = XmlUtility.DeserializeToObject<OptimizeElementConfig>(xmlContext);
            }


        }
        public void loade(string xmlContext, string context)
        {
            OptimizationConfig(xmlContext);
            OptimizationElementConfig(context);
        }

        #region 判断优选结果是否存在 未迁移
        /// <summary>
        /// 读取数据来源配置
        /// </summary>
        /// <returns></returns>
        //public bool IsXmlconfig(string xmlContext, string context)
        //{
        //    try
        //    {
        //        //BUG 这里有问题，正常运行下不会获取本地的配置文件，肯定出现错误
        //        XmlDocument dataDocument = new XmlDocument();
        //        dataDocument.Load(BllDataHandle.GetCurrentProgramPath() + @"Config\personel\MultipleConfig.xml");

        //        XmlDocument xmlDocumentConfig = new XmlDocument();
        //        xmlDocumentConfig.Load(BllDataHandle.GetCurrentProgramPath() + @"Config\personel\Multiple\" + dataContext.DataLayerAns.SourceCode + ".xml");
        //        MultipleModel(xmlDocumentConfig.OuterXml);
        //        MultipleSginModel(dataDocument.OuterXml);
        //    }
        //    catch (Exception)
        //    {
        //        dataContext.InteractiveShow.LogShow("加载相同文书合并配置失败，请检查配置文件！" + dataContext.DataLayerAns.SourceCode + ".xml 和 MultipleConfig.xml");

        //    }

        //    //SqlCommonUtil<CaseCenterModel> sqlCommonUtil = new SqlCommonUtil<CaseCenterModel>();
        //    bool state = false;
        //    //加载配置
        //    DAL_An_anjianxinxi dAL_An_Anjianxinxi = new DAL_An_anjianxinxi();
        //    List<An_anjianxinxi> anjianxinxiList = dAL_An_Anjianxinxi.GetList(dataContext.DataLayerOpt.CaseId);
        //    //调整的数据，不应该出现案件信息列表为空的情况，如果为空则表示数据错误
        //    if (anjianxinxiList != null && anjianxinxiList.Count > 0)
        //    {
        //        //dataContext.DataLayerOpt.ElementOptimizationResults = new CaseCenterModel()
        //        //{
        //        //    CaseCode = anjianxinxiList[0].Anhao,
        //        //    CaseID = anjianxinxiList[0].Anjianid,
        //        //    CaseOnlyID = anjianxinxiList[0].Anjianid,
        //        //    CaseType = anjianxinxiList[0].Anjianleixing,
        //        //    State = Convert.ToString(anjianxinxiList[0].Zhuangtai),
        //        //    UpdateTime = Convert.ToString(anjianxinxiList[0].Gengxinshijian),
        //        //    CourtID = anjianxinxiList[0].Fayuanid,

        //        //};
        //        //查询案件存储的结果数据;
        //        DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
        //        var anjiancunchuModels = anjiancunchudal.GetList(anjianxinxiList[0].Anjianid);
        //        if (anjiancunchuModels.Count > 0)
        //        {
        //            dataContext.InteractiveShow.LogShow("查询到优选结果");
        //            List<OptimizationElementResult> results = new List<OptimizationElementResult>();
        //            foreach (var itemmo in anjiancunchuModels)
        //            {
        //                results.Add(new OptimizationElementResult()
        //                {
        //                    CaseID = itemmo.Anjianid,
        //                    ER_Code = itemmo.Wenjianid,
        //                    ER_ID = itemmo.Anjiancunchuid,
        //                    ER_TypeCode = itemmo.Cunchuleixing
        //                });
        //            }
        //            base.dataLayerStores.caseCenterModel.optimizationElementResultList = results;
        //            state = true;
        //        }
        //        else
        //        {
        //            InteractiveShow.LogShow("没有优选结果");
        //        }
        //        base.dataLayerStores.Caseid = anjianxinxiList[0].Anjianid;
        //    }
        //    return state;
        //}
        #endregion


        /// <summary>
        /// 获取父集目录
        /// </summary>
        /// <param name="text">路径</param>
        /// <returns></returns>
        public string LasdString(string text)
        {
            string value = "";
            string[] str = text.Split('/'); //根据特定符号截取为字符串数组；
            string temp = str[str.Length - 1]; //取出数组最后一位；
            value = text.Substring(0, text.Length - temp.Length - 1);   //整个文件全名，去掉数据最后一位，剩下文件名；
            return value;
        }
        #endregion

        #region DataModel转换XML
        //这个转换方法有错误，导致要素无法正常转换，调整为XmlUtility.DataModelByXml这个类的方法；
        ///// <summary>
        ///// DataModel转换XML
        ///// </summary>
        ///// <param name="dataModelList">实体对象</param>
        ///// <returns></returns>
        //public XmlDocument DataModelByXml(List<DataModel> dataModelList, string parentID = "")
        //{
        //    if (dataModelList.Count > 0)
        //    {
        //        dataModelList = dataModelList.Where(a => a.State != "0").ToList();
        //    }
        //    foreach (DataModel dataModel in dataModelList.Where(a => a.ID == a.ParentId))
        //    {
        //        dataModel.ParentId = "";
        //    }
        //    XmlDocument xmlDocument = new XmlDocument();
        //    DataModel dataModelRoot = dataModelList.FirstOrDefault(a => a.ParentId == parentID);

        //    XmlElement xmlElementRoot = xmlDocument.CreateElement(dataModelRoot.XmlPath.Replace("/", ""));
        //    xmlElementRoot.SetAttribute("id", dataModelRoot.ID);
        //    if (dataModelRoot.AttributesList != null)
        //    {
        //        foreach (var attitem in dataModelRoot.AttributesList)
        //        {
        //            xmlElementRoot.SetAttribute(attitem.Name, attitem.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue);
        //        }
        //    }
        //    XmlNodeDocDataModel(xmlElementRoot, xmlDocument, dataModelRoot.ID, dataModelList);
        //    xmlDocument.AppendChild(xmlElementRoot);
        //    if (xmlDocument != null)
        //    {
        //        xmlDocument = xmlDocument;
        //    }
        //    return xmlDocument;
        //}

        ///// <summary>
        ///// 父子级别节点添加
        ///// </summary>
        ///// <param name="xmlElementRoot">父节点</param>
        ///// <param name="xmlDocument">数据对象</param>
        ///// <param name="parentID">上级ID</param>
        ///// <param name="dataModelList">数据源</param>
        //public void XmlNodeDocDataModel(XmlElement xmlElementRoot, XmlDocument xmlDocument, string parentID, List<DataModel> dataModelList)
        //{

        //    List<DataModel> chanNodelModelList = dataModelList.Where(a => a.ParentId == parentID).ToList();
        //    foreach (DataModel dataModel in chanNodelModelList)
        //    {
        //        string nodename = dataModel.XmlPath.Split('/')[dataModel.XmlPath.Split('/').Length - 1];
        //        if (string.IsNullOrEmpty(nodename))
        //        {
        //            nodename = dataModel.XmlPath.Replace("/", "");
        //        }

        //        Regex r = new Regex(@"\[[^,，。;；/]*?\]");
        //        MatchCollection mc = r.Matches(nodename);
        //        string name = "";
        //        if (mc.Count>0)
        //        {
        //            for (int i = 0; i < mc.Count; i++)
        //            {
        //                name = nodename.Replace(mc[i].Value, "");
        //            }
        //        }
        //        else
        //        {
        //            name = nodename;
        //        }


        //        XmlElement xmlElementNodel = xmlDocument.CreateElement(name);
        //        xmlElementNodel.SetAttribute("id", dataModel.ID);
        //        if (dataModel.AttributesList != null)
        //        {
        //            foreach (var attirValue in dataModel.AttributesList)
        //            {
        //                if (attirValue.sourceList.FirstOrDefault(a => a.IsCheck == "1") != null)
        //                {
        //                    string saveValue = attirValue.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
        //                    if (!string.IsNullOrEmpty(saveValue))
        //                    {
        //                        xmlElementNodel.SetAttribute(attirValue.Name, saveValue);
        //                    }
        //                }

        //            }
        //        }

        //        XmlNodeDocDataModel(xmlElementNodel, xmlDocument, dataModel.ID, dataModelList);
        //        xmlElementRoot.AppendChild(xmlElementNodel);

        //    }
        //}
        #endregion

        #region 数据源帮助类
        /// <summary>
        /// 计算当前元素在List中的第几位
        /// </summary>
        /// <param name="list">集合</param>
        /// <param name="name">值</param>
        /// <returns></returns>
        public int ListByCount(List<string> list, string name)
        {
            for (int i = 0; i < list.Count; i++)
            {
                if (name?.ToLower() == list[i])
                {
                    return i + 1;
                }
            }
            return 999;
        }
        /// <summary>
        /// 获取下级所有子节点
        /// </summary>
        /// <param name="dataModelList">数据源集合</param>
        /// <param name="dataModel">当前数据</param>
        /// <returns></returns>
        public List<DataModel> SubordinateDataModelList(List<DataModel> dataModelList, DataModel dataModel)
        {
            List<DataModel> dataList = new List<DataModel>();
            dataList.Add(dataModel);
            List<DataModel> datasModels = dataModelList.Where(a => a.ParentId == dataModel.ID && a.ID != dataModel.ID).ToList();
            foreach (DataModel model in datasModels)
            {
                List<DataModel> dataModelValueList = SubordinateDataModelList(dataModelList, model);
                dataList.AddRange(dataModelValueList);
            }
            return dataList;
        }

        /// <summary>
        /// 获取上级节点
        /// </summary>
        /// <param name="dataModelList">数据集合</param>
        /// <param name="dataModel">数据点</param>
        /// <returns></returns>
        public List<DataModel> ParendNodeDataModelList(List<DataModel> dataModelList, DataModel dataModel)
        {

            List<DataModel> dataList = new List<DataModel>();

            DataModel nodeDataModel = dataModelList.FirstOrDefault(a => a.ID == dataModel.ParentId);
            if (nodeDataModel != null)
            {

                List<DataModel> modeList = ParendNodeDataModelList(dataModelList, nodeDataModel);
                if (modeList.Count > 0)
                {
                    dataList.AddRange(modeList);
                }
                dataList.Add(nodeDataModel);
            }
            return dataList;

        }



        /// <summary>
        /// 清除节点下ID
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dataModelList"></param>
        public void DelectNodeByDataModel(string id, List<DataModel> dataModelList)
        {
            List<DataModel> datasModels = dataModelList.Where(a => a.ParentId == id).ToList();
            foreach (DataModel dataModel in datasModels)
            {
                dataModelList.Remove(dataModel);
                DelectNodeByDataModel(dataModel.ID, dataModelList);
            }
        }

        /// <summary>
        /// 重置信息ID
        /// </summary>
        /// <param name="dataModelList"></param>
        /// <param name="parentID"></param>
        public void DataModelIDByReset(List<DataModel> dataModelList, string parentID, string parentIDNew)
        {
            List<DataModel> dataList = dataModelList.Where(a => a.ParentId == parentID).ToList();
            foreach (DataModel dataModel in dataList)
            {
                string id = dataModel.ID;
                dataModel.ID = Snowflake.Instance().GetId().ToString();
                dataModel.ParentId = parentIDNew;
                DataModelIDByReset(dataModelList, id, dataModel.ID);
            }
        }

        //TODO:ZSW 证据与事实要素关系建立
        /// <summary>
        /// 重置信息ID并记录重置前后节点Id
        /// </summary>
        public void DataModelIDByResetAndRecord(List<DataModel> dataModelList, string parentID, string parentIDNew, List<EvidenctNodeRecord> nodeRecords, string recordType, out List<EvidenctNodeRecord> resultRecords)
        {
            if (nodeRecords == null)
                nodeRecords = new List<EvidenctNodeRecord>();
            List<DataModel> dataList = dataModelList.Where(a => a.ParentId == parentID).ToList();
            foreach (DataModel dataModel in dataList)
            {
                string id = dataModel.ID;
                dataModel.ID = Snowflake.Instance().GetId().ToString();
                dataModel.ParentId = parentIDNew;
                EvidenctNodeRecord resetRecord = new EvidenctNodeRecord();
                resetRecord.ResetBeforeId = id;
                resetRecord.ResetAfterId = dataModel.ID;
                resetRecord.RecoredType = recordType;
                string sfid = string.Empty;
                var sfidSource = dataModel.sourceData.sourceList.Where(x => x.SourceCode == "evidencedata").FirstOrDefault();
                if (sfidSource != null)
                {
                    sfid = sfidSource.SourceID;
                }
                resetRecord.EvidenctFileId = sfid;
                nodeRecords.Add(resetRecord);
                DataModelIDByResetAndRecord(dataModelList, id, dataModel.ID, nodeRecords, recordType, out resultRecords);
            }
            resultRecords = nodeRecords;
        }

        /// <summary>
        /// 补全Xpath路径值
        /// </summary>
        /// <param name="dataModelCaseElmentList">实体集合</param>
        /// <param name="path">路径集合</param>
        /// <returns></returns>
        public string CaseNodeUpdate(List<DataModel> dataModelCaseElmentList, string path)
        {
            DataModel dataModel = XmlUtility.ConditionFirstOrDefaultDataModel(dataModelCaseElmentList, "", path);
            if (path=="证据要素")
            {
                return "";
            }
            if (dataModel == null && path!="证据要素")
            {
                string xpath = "";
                List<string> pathList = path.Split("/").ToList();
                
                    pathList.RemoveAt(pathList.Count - 1);
                
                
                foreach (string nodename in pathList)
                {
                    if (xpath == "")
                    {
                        xpath = xpath + nodename;
                    }
                    else
                    {
                        xpath = xpath + "/" + nodename;
                    }
                }
                string uid = "";
                
                if (XmlUtility.ConditionFirstOrDefaultDataModel(dataModelCaseElmentList, "", xpath) == null)
                {
                    uid = CaseNodeUpdate(dataModelCaseElmentList, xpath);
                }
                else
                {
                    uid = XmlUtility.ConditionFirstOrDefaultDataModel(dataModelCaseElmentList, "", xpath).ID;
                }
                if (string.IsNullOrEmpty(uid))
                {
                    return "";
                }
                string xmlpath = path;
                Regex r = new Regex(@"\[[^,，。;；/]*?\]");
                MatchCollection mc = r.Matches(xmlpath);
                for (int i = 0; i < mc.Count; i++)
                {
                    xmlpath = xmlpath.Replace(mc[i].Value, "");
                }
                DataModel dataModelCauseName = new DataModel();
                dataModelCauseName.ID = Snowflake.Instance().GetId().ToString();
                dataModelCauseName.XmlPath = xmlpath;
                dataModelCauseName.sourceData = new SourceData();
                dataModelCauseName.ParentId = uid;
                dataModelCauseName.sourceData.sourceList = new List<Source>();
                Source source = new Source();
                source.SourceCode = dataContext.DataLayerAns.SourceCode;
                source.IsCheck = "1";
                dataModelCauseName.sourceData.sourceList.Add(source);
                dataModelCaseElmentList.Add(dataModelCauseName);

                return dataModelCauseName.ID;
            }
            else
            {
                return dataModel.ID;
            }

        }

        /// <summary>
        /// 属性存在判定
        /// </summary>
        /// <param name="dataModelList">数据集合</param>
        /// <param name="dataModel">需要判定的节点</param>
        /// <returns></returns>
        public bool ISsameNode(List<DataModel> dataModelList, DataModel dataModel)
        {
           
            if (dataModel.AttributesList == null || dataModel.AttributesList.Count == 0)
            {
                return true;
            }

            foreach (DataModel dataSame in dataModelList)
            {
                //属性是否存在
                bool isexistence = false;
                foreach (var attitem in dataModel.AttributesList.Where(a => a.Name != "id"))
                {
                    if (dataSame.AttributesList == null)
                    {
                        isexistence = false;
                        break;
                    }
                    var attsame = dataSame.AttributesList.FirstOrDefault(a => a.Name == attitem.Name);
                    if (attsame != null)
                    {
                        Source source = attsame.sourceList.FirstOrDefault(a => a.SaveValue == attitem.sourceList.FirstOrDefault(b => b.IsCheck == "1").SaveValue);
                        if (source != null)
                        {
                            isexistence = true;
                        }
                        else
                        {
                            isexistence = false;
                            break;
                        }
                    }
                    else
                    {
                        isexistence = false;
                        break;
                    }
                }
                if (isexistence)
                {
                    return true;
                }
            }

            return false;
        }
        /// <summary>
        /// 刷新ID
        /// </summary>
        /// <param name="dataModelElementList">需要刷新的集合</param>
        /// <param name="Parentid">父级id</param>
        /// <param name="ParentidNew">新父级ID</param>
        public void RestructureElment(List<DataModel> dataModelElementList, string Parentid, string ParentidNew)
        {
            List<DataModel> dataModelList = dataModelElementList.Where(a => a.ParentId == Parentid).ToList();
            foreach (DataModel dataModel in dataModelList)
            {
                string idparent = dataModel.ID;
                dataModel.ID = Snowflake.Instance().GetId().ToString();
                dataModel.ParentId = ParentidNew;
                RestructureElment(dataModelElementList, idparent, dataModel.ID);
            }

        }
        #endregion

        #region 数据条件判定
        /// <summary>
        /// 对数据条件进行判定
        /// </summary>
        /// <param name="conditionList">条件组</param>
        /// <returns></returns>
        public bool ConditionDetermine(List<Condition> conditionList)
        {
            bool determine = false;
            foreach (Condition condition in conditionList)
            {
                XmlDocument xmlDocument = XmlUtility.DataModelByXml(dataContext.DataLayerAns.ElementAnalsisDataModelResults.First().Value);
                //XmlDocument xmlDocument = dataContext.DataLayerAns.AnalysisResultsXml;
                if (condition.operation.ToLower().IndexOf("matching") > -1)
                {
                    //进行匹配操作
                    XmlNode xmlNode = xmlDocument.SelectSingleNode(condition.where);
                    if (string.IsNullOrEmpty(xmlNode.Value))
                    {
                        string code = Regex.Match("[\u4E00 -\u9FFF] + ", condition.operation, RegexOptions.Singleline).Value;
                        determine = RuleParseClass.IsMatch(code, xmlNode.Value);
                    }
                    if (determine)
                    {
                        return determine;
                    }
                }
                else if (!string.IsNullOrEmpty(condition.RegCode)) 
                {
                    XmlNode xmlNode = xmlDocument.SelectSingleNode(condition.where);
                    if (xmlNode!=null&&string.IsNullOrEmpty(xmlNode.Value))
                    {
                        string value = RuleParseClass.GetParseRegCodeValue(condition.RegCode, xmlNode.Value);
                        switch (condition.operation)
                        {
                            case "=":
                                determine = value == condition.value;
                                break;
                            case "!=":
                                determine = value != condition.value;
                                break;
                            default:
                                break;
                        }
                    }
                    if (determine)
                    {
                        return determine;
                    }
                }
                else
                {
                    XmlNodeList xmlNodeList = xmlDocument.SelectNodes(condition.where.Replace("]", "") + " " + condition.operation + "'" + condition.value + "']");
                    if (xmlNodeList.Count > 0)
                    {
                        determine = true;
                        if (condition.ConditionList.Count > 0)
                        {
                            determine = ConditionDetermine(condition.ConditionList);
                        }
                        if (determine)
                        {
                            return determine;
                        }
                    }
                }
            }
            return determine;
        }

        public bool ConditionDetermine(List<Condition> conditionList,List<DataModel> optDataModels)
        {
            bool determine = false;
            foreach (Condition condition in conditionList)
            {
                XmlDocument xmlDocument = XmlUtility.DataModelByXml(optDataModels);
                if (condition.operation.ToLower().IndexOf("matching") > -1)
                {
                    //进行匹配操作
                    XmlNode xmlNode = xmlDocument.SelectSingleNode(condition.where);
                    if (string.IsNullOrEmpty(xmlNode.Value))
                    {
                        string code = Regex.Match("[\u4E00 -\u9FFF] + ", condition.operation, RegexOptions.Singleline).Value;
                        determine = RuleParseClass.IsMatch(code, xmlNode.Value);
                    }
                    if (determine)
                    {
                        return determine;
                    }
                }
                else if (!string.IsNullOrEmpty(condition.RegCode))
                {
                    XmlNode xmlNode = xmlDocument.SelectSingleNode(condition.where);
                    if (string.IsNullOrEmpty(xmlNode.Value))
                    {
                        string value = RuleParseClass.GetParseRegCodeValue(condition.RegCode, xmlNode.Value);
                        switch (condition.operation)
                        {
                            case "=":
                                determine = value == condition.value;
                                break;
                            case "!=":
                                determine = value != condition.value;
                                break;
                            default:
                                break;
                        }
                    }
                    if (determine)
                    {
                        return determine;
                    }
                }
                else
                {
                    XmlNodeList xmlNodeList = xmlDocument.SelectNodes(condition.where.Replace("]", "") + " " + condition.operation + "'" + condition.value + "']");
                    if (xmlNodeList.Count > 0)
                    {
                        determine = true;
                        if (condition.ConditionList.Count > 0)
                        {
                            determine = ConditionDetermine(condition.ConditionList, optDataModels);
                        }
                        if (determine)
                        {
                            return determine;
                        }
                    }
                }
            }
            return determine;
        }
        #endregion

        /// <summary>
        /// 数据优选操作
        /// </summary>
        /// <param name="dataModelAsis">分析完毕数据</param>
        /// <param name="dataModelOP">上次优选结果数据</param>
        /// <param name="xmllableConfig">优选配置</param>     
        public void OptimizationData(DataModel dataModelAsis, DataModel dataModelOP, Xmllable xmllableConfig, List<DataModel> dataModelSingOpList, List<DataModel> dataModelAsisList, List<Sourcedatadefine> Sourcedatadefine)
        {

            if (dataModelOP==null || dataModelOP.sourceData == null)
            {
                string xmlpath = "";
                for (int i = 0; i < xmllableConfig.Xmlpath.Split('/').Length - 1; i++)
                {
                    if (xmlpath == "")
                    {
                        xmlpath = xmllableConfig.Xmlpath.Split('/')[i];
                    }
                    else
                    {
                        xmlpath = xmlpath + "/" + xmllableConfig.Xmlpath.Split('/')[i];
                    }
                }
                string parentid = "";
                if (!string.IsNullOrWhiteSpace(dataModelAsis.ParentId))
                {
                    if (dataModelSingOpList.FirstOrDefault(a => a.XmlPath == xmlpath || a.XmlPath == "/" + xmlpath)!=null) 
                    {
                        parentid = dataModelSingOpList.FirstOrDefault(a => a.XmlPath == xmlpath || a.XmlPath == "/" + xmlpath).ID;
                    }
                    if (string.IsNullOrEmpty(parentid))
                    {
                       string xmlpathtemp  = xmlpath.Split(new string[] { @"案件审理阶段/" }, StringSplitOptions.RemoveEmptyEntries)[1];
                        if (dataModelSingOpList.FirstOrDefault(a => a.XmlPath == xmlpathtemp || a.XmlPath == "/" + xmlpathtemp)!=null)
                        {
                            parentid = dataModelSingOpList.FirstOrDefault(a => a.XmlPath == xmlpathtemp || a.XmlPath == "/" + xmlpathtemp).ID;
                        }
                    }
                    
                }
                if (string.IsNullOrEmpty(parentid))
                {
                    return;
                }
                List<DataModel> dataModelAsList = new List<DataModel>();
                dataModelAsList = SubordinateDataModelList(dataModelAsisList, dataModelAsis);
                string messagss= JsonConvert.SerializeObject(dataModelAsList);
                dataModelAsList.FirstOrDefault(a => a.XmlPath == dataModelAsis.XmlPath).ParentId = parentid;
                dataModelSingOpList.AddRange(dataModelAsList);
                dataModelSingOpList.RemoveAll(x => !x.sourceData.sourceList.Any(x => x.IsCheck == "1"));
            }
            else
            {
                if (dataModelOP.sourceData != null)
                {
                    Source source = dataModelOP.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1");
                    if (source != null)
                    {                        
                        string soursnameop = dataModelOP.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SourceCode;
                        string soursnameasis = dataContext.DataLayerAns.SourceCode;
                        if (Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == soursnameop.ToLower()) != null)
                        {
                            string soursnameopid = Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == soursnameop.ToLower()).id.ToString();
                            string soursnameasisid = Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == soursnameasis.ToLower()).id.ToString();
                            int opsum = ListByCount(xmllableConfig.Priority.Split('>').ToList(), soursnameopid);
                            int assum = ListByCount(xmllableConfig.Priority.Split('>').ToList(), soursnameasisid);

                            switch (xmllableConfig.Type)
                            {
                                case "a":
                                    SginOptimizationData sginOptimizationData = new SginOptimizationData(dataContext) { mergeModel=mergeModel, Sourcedatadefine = Sourcedatadefine };
                                    sginOptimizationData.Optimization(dataModelAsis, dataModelOP, opsum, assum, xmllableConfig, soursnameopid, soursnameasisid);
                                    break;
                                case "b":
                                    SginOptimizationData sginOptimizationData_b = new SginOptimizationData(dataContext) { mergeModel = mergeModel, Sourcedatadefine = Sourcedatadefine };
                                    sginOptimizationData_b.Optimization(dataModelAsis, dataModelOP, opsum, assum, xmllableConfig, soursnameopid, soursnameasisid);
                                    break;
                                case "c":
                                    SpecifiedDataOptimizationData specifiedDataOptimizationData = new SpecifiedDataOptimizationData(dataContext) { mergeModel = mergeModel };
                                    specifiedDataOptimizationData.Optimization(dataModelAsis, dataModelOP, opsum, assum, xmllableConfig, soursnameopid, soursnameasisid);
                                    break;
                                case "d":
                                    QuantityOptimizationData quantityOptimizationData = new QuantityOptimizationData(dataContext) { mergeModel = mergeModel, Sourcedatadefine = Sourcedatadefine }; 
                                    quantityOptimizationData.Optimization(dataModelAsis, dataModelOP, opsum, assum, xmllableConfig, soursnameopid, soursnameasisid);
                                    break;
                                case "e":
                                    SginOptimizationData sginOptimizationData_e = new SginOptimizationData(dataContext) { mergeModel = mergeModel, Sourcedatadefine = Sourcedatadefine }; 
                                    sginOptimizationData_e.Optimization(dataModelAsis, dataModelOP, opsum, assum, xmllableConfig, soursnameopid, soursnameasisid);
                                    break;
                                case "f":
                                    SingleDataSourceOptimizationData singleDataSourceOptimizationData = new SingleDataSourceOptimizationData(dataContext) { mergeModel = mergeModel, Sourcedatadefine= Sourcedatadefine }; 
                                    singleDataSourceOptimizationData.Optimization(dataModelAsis, dataModelOP, opsum, assum, xmllableConfig, soursnameopid, soursnameasisid);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 获取XML数据
        /// </summary>
        /// <param name="id">XMLid</param>
        /// <returns></returns>
        public XmlDocument ReadDataXML(string id)
        {
            XmlDocument xmlDocument = new XmlDocument();
            dynamic message = HttpHelp.HttpGet(SaveUrl + "/api/XmlDataManage/GetXmlContent/" + id, "");
            string messagex = message;
            xmlDocument.LoadXml(messagex.Replace("&#x13;", "").Replace("&#x14;", "").Replace("&#x15;", "").Replace("&#xD;", ""));
            return xmlDocument;
        }

        /// <summary>
        /// 过滤数据源信息
        /// </summary>
        /// <param name="caseElementDataModelList">案件过程数据</param>
        public void FilterCaseElment(List<DataModel> caseElementDataModelList)
        {
            List<DataModel> resultDataModel = new List<DataModel>();
            for (int i = 0; i < caseElementDataModelList.Count; i++)
            {
                Xmllable xmllableCofigs = OptimizConfig.XmllableList.FirstOrDefault(a => a.Xmlpath == caseElementDataModelList[i].XmlPath);
                if (xmllableCofigs != null)
                {
                    string priority = xmllableCofigs.Priority;
                    string soursnameasisid = OptimizConfig.Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).id.ToString();
                    int assum = ListByCount(priority.Split('>').ToList(), soursnameasisid);
                    if (assum == 999)
                    {
                        resultDataModel.AddRange(SubordinateDataModelList(caseElementDataModelList, caseElementDataModelList[i]));
                    }
                    else
                    {
                        if (caseElementDataModelList[i].State == "0")
                        {
                            resultDataModel.Add(caseElementDataModelList[i]);
                        }

                    }
                }
            }
            foreach (DataModel dataModel in resultDataModel)
            {
                caseElementDataModelList.Remove(dataModel);
            }
        }

        /// <summary>
        /// 模块执行进度
        /// </summary>
        /// <param name="moduleName">模块名称</param>
        /// <param name="nvalue">进度值</param>
        public void SetModuleProcess(string moduleName, int nvalue, MainInputParameterModel inputParameterModel)
        {
            dataContext.InteractiveShow.ModuleProcessShow?.Invoke(moduleName, nvalue,inputParameterModel);
        }

        /// <summary>
        /// 获取要素中的阶段数据
        /// </summary>
        /// <param name="stageConfigList"></param>
        /// <param name="dataModelList"></param>
        /// <returns></returns>
        public List<StageProcessModel> LoadeStageData(StageConfig stageConfig,List<DataModel> dataModelList) 
        {
            List<StageProcessModel> stageProcessModelList = new List<StageProcessModel>();
            foreach (StageModel stageModel in stageConfig.stageModelList)
            {
                DataModel dataModel = XmlUtility.ConditionFirstOrDefaultDataModel(dataModelList, "", stageModel.path);
                if (dataModel!=null)
                {
                    StageProcessModel stageProcessModel = new StageProcessModel();
                    stageProcessModel.id = Convert.ToInt32(stageModel.id);
                    stageProcessModel.dataModel = dataModel;
                    stageProcessModel.Analysisresults = true;
                    stageProcessModel.path = stageModel.path;
                    stageProcessModel.stageName = stageModel.value;
                    stageProcessModelList.Add(stageProcessModel);
                }
            }
            return stageProcessModelList;
        }

    }
}
 